import { defineStore } from 'pinia';
import { store } from '@/store';
import { encryption } from '@/utils';
import { ACCESS_TOKEN, CURRENT_USER, IS_LOCKSCREEN, REFRESH_TOKEN } from '@/store/mutation-types';

import { getUserInfo } from '@/api/system/user';

import { loginByMobile, loginByUsername, refreshToken } from '@/api/login';
import { storage } from '@/utils/Storage';
import { Result } from '@/utils/http/axios/types';
import { ResultEnum } from '@/enums/httpEnum';

export interface IUserState {
  access_token: string;
  refresh_token: string;
  username: string;
  welcome: string;
  avatar: string;
  permissions: string[];
  info: any;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    access_token: storage.get(ACCESS_TOKEN, ''),
    refresh_token: storage.get(REFRESH_TOKEN, ''),
    username: '',
    welcome: '',
    avatar: '',
    permissions: [],
    info: storage.get(CURRENT_USER, {}),
  }),
  getters: {
    getAccessToken(): string {
      return this.access_token;
    },
    getRefreshToken(): string {
      return this.access_token;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getNickname(): string {
      return this.username;
    },
    getPermissions(): string[] {
      return this.permissions;
    },
    getUserInfo(): object {
      return this.info;
    },
  },
  actions: {
    setAccessToken(access_token: string) {
      this.access_token = access_token;
    },
    setRefreshToken(refresh_token: string) {
      this.refresh_token = refresh_token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    setUserInfo(info) {
      this.info = info;
    },
    // 登录
    async loginByUsername(userInfo) {
      try {
        const user = encryption({
          data: userInfo,
          key: 'SHmfaQwNX6nzb3Ee',
          param: ['password'],
        });
        const response = await loginByUsername(
          user.username,
          user.password,
          user.code,
          user.randomStr
        );
        const { access_token, refresh_token, user_info } = response;
        if (access_token) {
          const ex = 7 * 24 * 60 * 60;
          storage.set(ACCESS_TOKEN, access_token, ex);
          storage.set(REFRESH_TOKEN, refresh_token, ex);
          storage.set(CURRENT_USER, user_info, ex);
          storage.set(IS_LOCKSCREEN, false);
          this.setAccessToken(access_token);
          this.setRefreshToken(refresh_token);
          this.setUserInfo(user_info);
        }
        const code: string = ResultEnum.SUCCESS;
        const result: Result = {
          code: code,
          msg: '登录成功',
        };
        return Promise.resolve(result);
      } catch (e) {
        return Promise.reject(e);
      }
    },
    // 根据手机号登录
    async loginByPhone(smsForm) {
      return new Promise((resolve, reject) => {
        loginByMobile(smsForm)
          .then((response) => {
            this.setAccessToken(response.access_token);
            this.setRefreshToken(response.refresh_token);
            const ex = 7 * 24 * 60 * 60;
            storage.set(ACCESS_TOKEN, response.access_token, ex);
            storage.set(REFRESH_TOKEN, response.refresh_token, ex);
            storage.set(CURRENT_USER, response.user_info, ex);
            storage.set(IS_LOCKSCREEN, false);
            this.setUserInfo(response);
            const code: string = ResultEnum.SUCCESS;
            const result: Result = {
              code: code,
              msg: '登录成功',
            };
            resolve(result);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 刷新token
    async refreshToken() {
      return new Promise((resolve, reject) => {
        refreshToken(this.getRefreshToken)
          .then((response) => {
            const ex = 7 * 24 * 60 * 60;
            storage.set(ACCESS_TOKEN, response.access_token, ex);
            storage.set(REFRESH_TOKEN, response.refresh_token, ex);
            storage.set(CURRENT_USER, response.user_info, ex);
            const code: string = ResultEnum.SUCCESS;
            const result: Result = {
              code: code,
              msg: '刷新成功',
            };
            resolve(result);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    GetInfo() {
      const that = useUserStore(store);
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then((res) => {
            const result = res;
            if (result.permissions && result.permissions.length) {
              const permissionsList = result.permissions;
              that.setPermissions(permissionsList);
              that.setUserInfo(result);
            } else {
              reject(new Error('getInfo: permissionsList must be a non-null array !'));
            }
            that.setAvatar(result.avatar);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 登出
    async logout() {
      this.setPermissions([]);
      this.setUserInfo('');
      storage.remove(ACCESS_TOKEN);
      storage.remove(CURRENT_USER);
      return Promise.resolve('');
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWidthOut() {
  return useUserStore(store);
}
